<template>
  <div class="container">
    <div class="login">
      <!-- 新增标题 -->
      <h2 style="text-align: center; margin-bottom: 20px;">武汉交投康养人脸识别系统</h2>
      <el-form :model="loginForm" :rules="loginRules" ref="loginFormRef" label-width="80px" v-if="!loginSuccess">
        <el-form-item label="账号" prop="account">
          <el-input v-model="loginForm.account"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="loginForm.password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin" class="login-btn">登录</el-button>
        </el-form-item>
      </el-form>
      <!-- 登录成功后的选项页面 -->
      <div v-if="loginSuccess" class="action-btns">
        <el-button class="action-btn" @click="goToFaceRecognition" style="margin-left: 10px;">人脸识别验证</el-button>
        <el-button class="action-btn" @click="goToAdminPage">后台管理</el-button>
        <el-button class="action-btn" @click="handleSave">添加人脸</el-button>
        <el-button class="action-btn" @click="logout">退出</el-button>
      </div>

    </div>
    <!-- 弹窗部分保持不变 -->
    <div ref="effetAdd">
      <!-- 添加/修改-->
      <el-dialog
          :title="saveAndUpdateTitle"
          :visible.sync="saveAndUpdateDialog"
          :before-close="handleClose"
          width="600px"
      >
        <el-form :model="faceObj" :rules="rules" ref="ruleForm" label-width="80px">

          <input type="hidden" v-model="faceObj.fid"></input>

          <el-form-item label="人脸名称" prop="faceName">
            <el-input placeholder="必填项" v-model="faceObj.faceName"></el-input>
          </el-form-item>

          <el-form-item label="人脸状态" style="margin-bottom: 30px" prop="faceStatus">
            <el-select style="width: 100%;" v-model="faceObj.faceStatus" placeholder="请选择">
              <el-option label="启用" :value="0"></el-option>
              <el-option label="禁用" :value="1"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="人脸数据" class="login-mid-mid" prop="faceBase">
            <!--捕获人脸区域-->
            <div class="savevideoCamera-canvasCamera " style="margin-top: -60px;" ref="effetAdd">

              <el-input type="hidden" v-model="faceObj.faceBase"></el-input>
            </div>

            <!--拍照显示区域-->
            <div class="savefaceBase" id="faceBase">

            </div>

            <!--按钮区域-->
            <div class="saveface-btn" v-if="addFaceText === 'success'">
              <el-tag type="success">录入完成</el-tag>
            </div>
            <div class="saveface-btn" v-else>
              <el-tag>{{addFaceText === '人脸开始检测'?'头部请上下左右转动':addFaceText}}</el-tag>
            </div>

          </el-form-item>


          <el-form-item label="备注">
            <el-input placeholder="非必填" type="textarea" v-model="faceObj.remark"></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
            <el-button @click="resetForm('ruleForm')">重置</el-button>
          </el-form-item>


        </el-form>

      </el-dialog>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loginForm: {
        account: '',
        password: ''
      },
      loginRules: {
        account: [
          {required: true, message: '请输入账号', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'}
        ]
      },
      loginSuccess: false,
      // 新增的变量，从 index.vue 复制过来需要的部分
      size: 5,
      current: 1,
      total: 0,
      videoWidth: 200,
      videoHeight: 200,
      faceImgState: false,
      searchFace: {
        faceName: '',
        faceStatus: ''
      },
      tableData: [],
      selectImgDialog: false,
      currentImg: '',
      saveAndUpdateDialog: false,
      saveAndUpdateTitle: '',
      faceObj: {
        fid: null,
        faceName: '',
        faceBase: '',
        faceStatus: 0,
        remark: '',
        addAndUpdateState: false,
      },
      rules: {
        faceName: [
          {required: true, message: '请输入人脸名称', trigger: 'blur'},
          {min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur'}
        ],
        faceBase: [{required: true, message: '人脸数据不能为空'}]
      },
      faceOption: {},
      cameraState: false,
      // 第一次加载标记
      addFaceLoading: false,
      addFaceText: ''
    };
  },
  watch: {
    saveAndUpdateDialog: {
      handler(newValue, oldValue) {
        this.$nextTick(() => {
          if (newValue) {
            if (this.addFaceLoading) {
              this.addFaceText = '';
              if (this.addAndUpdateState) {
                this.faceObj.faceBase = '';
              }
              this.$faceEffet.restart();
              return;
            }
            // 添加日志检查
            console.log('effetAdd element:', this.$refs.effetAdd);
            if (this.$refs.effetAdd) {
              this.$faceEffet.init({
                el: this.$refs.effetAdd,
                type: 'addFace',
                addFaceDistance: 28, // 人脸距离屏幕的距离
                callBack: this.callBack
              });
              this.addFaceLoading = true;
            } else {
              console.error('effetAdd element not found');
            }
          } else {
            this.$faceEffet.close();
          }
        });
      }
    }
  },
  methods: {
    handleLogin() {
      this.$refs.loginFormRef.validate((valid) => {
        if (valid) {
          this.$http.post('/user/login', this.loginForm).then((res) => {
            if (res.code === 200) {

              localStorage.setItem("face_token", res.token);
              localStorage.setItem("username", res.name);
              this.loginSuccess = true;
              this.$message.success(res.msg);

            } else {
              this.$message.error('登录失败');
            }
          }).catch((error) => {
            this.$message.error('登录失败');
          });
        }
      });
    },
    //
    goToFaceRecognition() {
      this.$router.push('/face-login');
    },
    // 后台管理
    goToAdminPage() {
      this.$router.push("/home")
    },
    // 新增的方法，从 index.vue 复制过来需要的部分
    callBack(data) {
      Promise.all(data.base64Array).then((base64Strings) => {
        this.addFaceText = data.progressMessage;
        this.faceObj.faceBase = base64Strings[0] || '';
        if (this.addFaceText === 'success') {
          let faceBase = document.getElementById("faceBase");
          faceBase.innerHTML = "<img src='" + this.faceObj.faceBase + "' />";
        }
      }).catch((error) => {
        console.error("Error resolving promises:", error);
      });
    },
    // 增加|修改
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$http.post("/face/" + (this.addAndUpdateState ? 'save' : 'update'), this.faceObj).then(res => {
            this.$message({
              showClose: true,
              message: res.msg,
              type: 'success',
              duration: 3000
            });
            // 这里可能需要根据实际情况调整获取列表的逻辑
            // this.getFaceList();
            this.saveAndUpdateDialog = false;
          });
        } else {
          return false;
        }
      });
    },
    // 重置表单
    resetForm(formName) {
      let faceBase = document.getElementById("faceBase");
      faceBase.innerHTML = "";
      this.$refs[formName].resetFields();
    },
    // 查看人脸
    selectImg(faceBase) {
      this.selectImgDialog = true;
      this.currentImg = faceBase;
    },
    // 获取人脸列表
    getFaceList() {
      this.$http.get('/face/faceList', {
        params: {
          current: this.current,
          size: this.size,
          faceName: this.searchFace.faceName,
          faceStatus: this.searchFace.faceStatus
        }
      }).then(res => {
        console.log("响应结果", JSON.stringify(res));
        this.tableData = res.data.records;
        this.size = res.data.size;
        this.current = res.data.current;
        this.total = res.data.total;
      });
    },
    // 分页
    handleSizeChange(val) {
      this.size = val;
      this.getFaceList();
    },
    // 分页
    handleCurrentChange(val) {
      this.current = val;
      this.getFaceList();
    },
    // 关闭弹出层
    handleClose() {
      this.saveAndUpdateDialog = false;
      this.cameraState = false;
      this.resetForm('ruleForm');
    },
    // 设置按钮的延迟加载
    setCameraState() {
      setTimeout(() => {
        this.cameraState = true;
      }, 1500);
    },
    // 添加
    handleSave() {
      this.setCameraState();
      this.addAndUpdateState = true;
      this.saveAndUpdateDialog = true;
      this.saveAndUpdateTitle = '添加人脸';
    },
    // 退出登录
    logout() {
      localStorage.removeItem("face_token");
      localStorage.removeItem("username");
      this.loginSuccess = false;
      this.$message.success('已退出登录');
    }
  }
};
</script>

<style>
@import "./index.css";
</style>